//单例模式

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//饿汉模式
class HungerTest{
    private static HungerTest test=new HungerTest();

    private HungerTest(){
        ;
    }
    public static HungerTest getInstance(){
        return test;
    }
}
//懒汉模式
class LazyTest{
    //防止指令重排序问题
    private volatile static LazyTest test=null;

    public static LazyTest getInstance(){
        if(test==null){
            synchronized (LazyTest.class){
                if(test==null){
                    test=new LazyTest();
                }
            }
        }
        return test;
    }
}
//使用枚举创建单例模式
enum TestEnum1{
    instance;
    public TestEnum1 getInstance1(){
        return instance;
    }
}
public class Test {
    public static void main(String[] args) {
        HungerTest hungerTest=HungerTest.getInstance();
        LazyTest lazyTest=LazyTest.getInstance();
        TestEnum1 testEnum1=TestEnum1.instance;

        //反射会导致单例模式，创建多的对象(枚举无法被反射)

        try {
            Class<?> c=Class.forName("HungerTest");
            Constructor<?>constructor=c.getConstructor();
            constructor.setAccessible(true);
            HungerTest hungerTest1=(HungerTest) constructor.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

}
